﻿@page "/test"
@layout EmptyLayout
@inject CaptchaService CaptchaService
@inject MessageService Message
<AntDesign.Card Title="验证码示例" Style="width:400px">
    <Flex Direction="FlexDirection.Horizontal" Align="@("Center")" Justify="@("Center")">
        <!-- 验证码图片 -->
        <img src="@_captchaImage" alt="验证码"
             style="cursor:pointer; height:50px; margin-bottom:20px;"
             @onclick="RefreshCaptcha" />

        <!-- 输入框 -->
        <AntDesign.Input @bind-Value="_userInput"
                         Placeholder="请输入验证码"
                         Style="width:80%; margin-bottom:20px;" />

        <!-- 验证按钮 -->
        <AntDesign.Button Type="ButtonType.Primary"
                          OnClick="ValidateCaptcha">
            验证
        </AntDesign.Button>
    </Flex>
</AntDesign.Card>

@code {
    private string _captchaCode;
    private string _captchaImage;
    private string _userInput;

    protected override void OnInitialized()
    {
        RefreshCaptcha();
    }

    private void RefreshCaptcha()
    {
        var (code, bytes) = CaptchaService.GenVCode(4); // 生成4位验证码
        _captchaCode = code;
        _captchaImage = $"data:image/gif;base64,{Convert.ToBase64String(bytes)}";
        StateHasChanged(); // 触发UI更新
    }

    private void ValidateCaptcha()
    {
        if (_userInput.Equals(_captchaCode, StringComparison.OrdinalIgnoreCase))
        {
            Message.Success("验证码正确");
            RefreshCaptcha(); // 验证成功后刷新验证码
        }
        else
        {
            Message.Error("验证码错误，请重试");
        }
    }
}